<template>
    <div>
        <!-- 面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 内容区域-->
        <el-card class="box-card">
        <!-- 搜索与添加区域-->
        <el-row :gutter="20">
            <el-col :span="10">
              <el-input placeholder="请输入内容" v-model="queryInfo.kw" clearable @clear="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="getkw"></el-button>
            </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="addroledialog">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 用户列表区域-->
        <el-table :data="userList" border stripe>
            <el-table-column label="序列" type="index"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="密码" prop="password"></el-table-column>
            <el-table-column label="性别" prop="sex" width="50px"></el-table-column>
            <el-table-column label="电话" prop="phone"></el-table-column>
            <el-table-column label="角色" prop="role"></el-table-column>
            <!-- <el-table-column label="ID" prop="roleid" width="60px"></el-table-column> -->
            <el-table-column label="操作" width="130px">
              <template slot-scope="scope">
                <!-- 修改按钮-->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row)"></el-button>
                <!-- 删除按钮-->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row._id)"></el-button>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.page"
      :page-sizes="[1, 2, 5, 8]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
        </el-card>
        <!-- 添加用户的对话框区域-->
        <el-dialog
          title="添加用户"
          :visible.sync="adddialogVisible"
          width="50%" @close="adddialogclosed">
          <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="70px">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-input v-model="addForm.sex"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <!-- <el-input v-model="addForm.role"></el-input> -->
              <el-select v-model="addForm.role" placeholder="请选择">
                <el-option
                  v-for="item in roletypeList"
                  :key="item.roleid"
                  :label="item.rolename"
                  :value="item.rolename">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="角色id" prop="roleid">
              <el-input v-model="addForm.roleid"></el-input>
            </el-form-item> -->
          </el-form>
          <!-- 底部区域-->
          <span slot="footer" class="dialog-footer">
            <el-button @click="adddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="adduser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑用户的对话框区域-->
        <el-dialog
          title="修改用户"
          :visible.sync="editdialogVisible"
          width="50%"
          @close="editdialogclosed">
          <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px">
            <el-form-item label="姓名">
              <el-input v-model="editForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="editForm.password"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="edituserInfo">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    // 验证手机号的自定义规则
    var checkphone = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regphone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regphone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的电话号码'))
    }
    return {
    // 获取用户列表的参数对象
      queryInfo: {
        page: 1,
        pagesize: 5,
        kw: ''
      },
      edit: '',
      // 所有用户信息
      userList: [],
      // 所有角色类型
      roletypeList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      adddialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        name: '',
        username: '',
        password: '',
        sex: '',
        phone: '',
        role: '',
        roleid: ''
      },
      // 添加表单的验证规则对象
      addFormrules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名的长度在2~10个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '用户名的长度在5~10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '密码的长度在5~15个字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入性别', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请输入角色(admin/teacher/student)', trigger: 'blur' }
        ],
        roleid: [
          { required: true, message: '请输入角色id{admin(3)/teacher(2)/student(1)}', trigger: 'blur' }
        ]
      },
      editFormrules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '密码的长度在5~15个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editdialogVisible: false,
      // 查询到的用户信息对象
      editForm: {}
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.post('/userlist/getInfoByPage', this.queryInfo)
      if (res.err === 0) {
        this.userList = res.info.list
        this.total = res.info.count
      } else {
        return this.$message.error('获取用户列表失败')
      }
      console.log(res)
      console.log(this.userList)
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.page = newPage
      this.getUserList()
    },
    // 搜索（模糊）查询
    async getkw() {
      const { data: res } = await this.$http.post('/userlist/getInfoBykw', this.queryInfo)
      if (res.err === 0) {
        this.userList = res.list
      } else {
        return this.$message.error('获取用户列表失败')
      }
      console.log(res)
    },
    // 监听添加用户对话框的关闭事件
    adddialogclosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 新增用户信息并提交事件
    adduser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的请求
        const { data: res } = await this.$http.post('/userlist/add', this.addForm)
        if (res.err !== 0) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.adddialogVisible = false
        // 重新加载数据
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showeditDialog(id) {
      console.log(id)
      this.editForm = id
      // window.sessionStorage.setItem('editid', id)
      // this.editForm.id = window.sessionStorage.getItem('editid')
      // const { data: res } = await this.$http.post('/userlist/getInfoByid', this.editForm)
      // if (res.err !== 0) {
      //   return this.$message.error('查询用户信息失败')
      // }
      // this.editForm = res.info.list
      this.editdialogVisible = true
      // this.$router.push('/edituser')
    },
    // 监听修改用户对话框的关闭事件
    editdialogclosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交事件
    edituserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起修改用户的请求
        console.log(this.editForm.phone)
        const { data: res } = await this.$http.post('/userlist/update',
          {
            _id: this.editForm._id,
            password: this.editForm.password,
            phone: this.editForm.phone
          })
        if (res.err !== 0) {
          this.$message.error('修改用户失败')
        }
        this.$message.success('修改用户成功')
        // 隐藏修改用户对话框
        this.editdialogVisible = false
        // 重新加载数据
        this.getUserList()
      })
    },
    // 根据Id删除用户
    async removeUserById(id) {
      const user = id
      console.log(user)
      // 弹窗询问用户是否删除数据
      const ref = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .catch(err => {
          return err
        })
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (ref !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.post('/userlist/del', { _id: user })
      if (res.err === 0) {
        this.$message.success('删除一条数据')
        this.getUserList()
      } else {
        return this.$message.error('删除用户失败')
      }
    },
    // 添加课程按钮事件
    async addroledialog() {
      const { data: res } = await this.$http.post('/all/role')
      if (res.err === 0) {
        this.roletypeList = res.list
      } else {
        return this.$message.error('获取角色列表失败')
      }
      console.log(res)
      this.adddialogVisible = true
    }
  }
}
</script>

<style lang="less" scoped>

</style>
